# backend/routers/login.py

# // 修改导入部分
from fastapi import APIRouter, Request, Form, Depends, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from backend.dependencies import get_db  # 使用绝对导入
from backend.models.models import User  # 使用绝对导入
from backend.auth import verify_password  # 添加导入

router = APIRouter()
# 删除这里的 templates 定义，将由 main.py 提供
templates = None

# 删除硬编码的用户
# VALID_USERS = {
#     "doctor": "123456"
# }

@router.get("/login", response_class=HTMLResponse)
async def login_form(request: Request):
    return templates.TemplateResponse("login.html", {"request": request, "error": None})

@router.post("/api/login")
async def api_login(
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    # API登录使用username
    user = db.query(User).filter(User.username == username).first()
    if user and verify_password(password, user.password_hash):
        response = JSONResponse(content={"message": "登录成功", "username": username, "role": user.role})
        response.set_cookie("user", username, path="/")
        response.set_cookie("role", user.role, path="/")
        return response
    raise HTTPException(status_code=401, detail="用户名或密码错误")

@router.post("/login", response_class=HTMLResponse)
async def login_submit(
    request: Request,
    username: str = Form(...),  # 这里的参数名虽然是username，但实际是doctor_name
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    # 医生登录使用doctor_name
    user = db.query(User).filter(User.doctor_name == username).first()
    if user is not None and verify_password(password, user.password_hash) and user.role == "doctor":
        response = RedirectResponse(url="/dashboard", status_code=302)
        response.set_cookie("user", user.username, path="/")  # 存储username
        response.set_cookie("role", user.role, path="/")  # 存储角色
        return response
    else:
        return templates.TemplateResponse("login.html", {"request": request, "error": "医生名称或密码错误"})